package com.eric.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.eric.domain.po.UnitName;
import com.eric.domain.po.table.UnitNameTableDef;
import com.eric.domain.vo.UnitNameVO;
import com.eric.service.UnitNameService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *  控制层。
 *
 * @author eric.deng
 * @since 2025-03-05
 */
@RestController
@Validated
@RequiredArgsConstructor
@RequestMapping("/unitName")
public class UnitNameController {


    private final UnitNameService unitNameService;    /**
     * 添加。
     *
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    @Transactional
    public SaResult save(@Validated @RequestBody UnitNameVO unitNameVO) {
        return unitNameService.saveOne(unitNameVO);
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    @Transactional
    public SaResult remove(@PathVariable Long id) {
       return unitNameService.removeOneById(id);
    }

    /**
     * 根据主键更新。
     *
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    @Transactional
    public SaResult update(@RequestBody UnitNameVO unitNameVO) {
        return unitNameService.updateOne(unitNameVO);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public  SaResult getUnitNameList() {
        List<UnitNameVO> unitNameVOList = unitNameService.queryChain().listAs(UnitNameVO.class);
        return SaResult.data(unitNameVOList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public SaResult getInfo(@PathVariable Integer id) {
        UnitName one = unitNameService.queryChain().where(UnitNameTableDef.UNIT_NAME.ID.eq(id)).one();
        return SaResult.data(BeanUtil.copyProperties(one, UnitNameVO.class));
    }

    @PostMapping("getInfoByName")
    public SaResult getInfoByName(@Validated @RequestBody UnitNameVO unitNameVO) {
        String unitName = unitNameVO.getUnitName();
        List<UnitName> unitNameList = unitNameService.queryChain().where(UnitNameTableDef.UNIT_NAME.UNIT_NAME_.like(unitName)).list();
        if (unitNameList.isEmpty()){
            return SaResult.error("未查询到该单位名称");        }
        List<UnitNameVO> unitNameVOList = BeanUtil.copyToList(unitNameList, UnitNameVO.class);
        return SaResult.data(unitNameVOList);
    }



}
